/* eslint-disable no-shadow */
/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable react-native/no-inline-styles */
import React, {useMemo, useState, useEffect} from 'react';
import {
  Text,
  View,
  Colors,
  Avatar,
  ActionSheet,
  Button,
  Picker,
  TabController,
} from 'react-native-ui-lib';
import Input from '@/components/Input';
import Select from '@/components/Select';
import {
  useWindowDimensions,
  ActivityIndicator,
  TextInput,
  DeviceEventEmitter,
  Keyboard,
} from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';
import {get, post, update, uploadFile} from '@/utils/request';
import {updateUserInfo, changepwd, join} from '@/utils/service';
import {connect, useDispatch} from 'react-redux';
import Mheader from '@/components/Mheader';
import {useRequest} from 'ahooks';
//Octicons
import Octicons from 'react-native-vector-icons/Octicons';
import AntdIcons from 'react-native-vector-icons/AntDesign';

const mobilePattern = /^1[3456789]\d{9}$/;

const EditInfo = props => {
  const Prefix = global.file;
  const dispatch = useDispatch();
  const {headUrl} = props.currentUser ?? {};
  const [header, setHeader] = useState(Prefix + headUrl);
  const [action, setAction] = useState({
    visible: false,
    onDismiss: () => {
      setAction(s => ({
        ...s,
        visible: false,
      }));
    },
  });

  async function changeheader(image) {
    let formData = new FormData();
    const name =
      'header' + image.modificationDate + '.' + image.mime.split('/')[1];
    const fileObj = {
      uri: image.path,
      type: image.mime,
      name,
    };
    setHeader(`data:${image.mime};base64,${image.data}`);
    // 将文件添加到 FormData 中
    formData.append('file', fileObj);
    const result = await uploadFile('/file/upload', formData);
    if (result?.code === 0) {
      const params = {headUrl: result?.data?.dataList[0]?.url};
      const userInfo = await updateUserInfo(params);
      dispatch?.({
        type: 'CHANGE_USERINFO',
        userInfo,
      });
    }
  }

  let {width} = useWindowDimensions();
  const [name, setName] = useState(props.currentUser.name);
  const [telephone, setTelephone] = useState(props.currentUser.telephone);

  let userprops = {
    placeholder: '填写您的名字或昵称',
    value: name,
    lefticon: 'user',
    allowClear: true,
    onChange: val => {
      setName(val);
    },
    onSubmitEditing: async () => {
      let userInfo = await updateUserInfo(
        {
          name,
        },
        //props.dispatch,
      );
      dispatch?.({
        type: 'CHANGE_USERINFO',
        userInfo,
      });
    },
  };

  let telephoneprops = {
    placeholder: '填写您的名字或昵称',
    value: telephone,
    lefticon: {
      type: 'FontAwesome',
      name: 'phone',
    },
    allowClear: true,
    onChange: val => {
      setTelephone(val);
    },
    onSubmitEditing: async () => {
      if (mobilePattern.test(telephone)) {
        let userInfo = await updateUserInfo(
          {
            name,
            telephone,
          },
          // props.dispatch,
        );
        dispatch?.({
          type: 'CHANGE_USERINFO',
          userInfo,
        });
      }
    },
  };

  return (
    <View center>
      <Mheader title={props.title} />

      <ActionSheet
        {...action}
        cancelButtonIndex={3}
        destructiveButtonIndex={0}
        options={[
          {
            label: <Text style={{color: Colors.colorTextBase}}>相机拍摄</Text>,
            onPress: () => {
              ImagePicker.openCamera({
                width: 300,
                height: 300,
                cropping: true,
                includeBase64: true,
              }).then(image => {
                changeheader(image);
              });
            },
          },
          {
            label: (
              <Text style={{color: Colors.colorTextBase}}>从手机选择</Text>
            ),
            onPress: () => {
              ImagePicker.openPicker({
                width: 300,
                height: 300,
                cropping: true,
                includeBase64: true,
              }).then(async image => {
                changeheader(image);
              });
            },
          },
          {
            label: <Text style={{color: Colors.red20}}>取消</Text>,
            onPress: () => {
              setAction(s => ({
                ...s,
                visible: false,
              }));
            },
          },
        ]}
        useNativeIOS
        dialogStyle={{
          backgroundColor: Colors.backgroundColor,
        }}
        containerStyle={{
          backgroundColor: Colors.backgroundColor,
        }}
      />

      <View
        style={{
          borderWidth: 6,
          borderColor: Colors.colorBgThird,
          width: 112,
          height: 112,
        }}
        marginT-24
        marginB-30
        br100>
        <Avatar
          source={{
            uri: header,
          }}
          size={100}
          label={header ? null : name.charAt(0)}
          onPress={() => {
            setAction(s => ({
              ...s,
              visible: true,
              title: '修改头像',
            }));
          }}
        />
      </View>

      <View row marginB-12 left width={width / 1.2}>
        <Text subheading>名字:</Text>
      </View>
      <Input {...userprops} />

      <View row marginB-12 marginT-24 left width={width / 1.2}>
        <Text
          subheading
          style={{
            color: mobilePattern.test(telephone)
              ? Colors.subheadingColor
              : '#ff4800',
          }}>
          电话号码:
        </Text>
      </View>
      <Input {...telephoneprops} />

      <View row marginB-12 marginT-24 left width={width / 1.2}>
        <Text body>*点击软键盘确定保存</Text>
      </View>
    </View>
  );
};

const ChangePwd = ({navigation, title}) => {
  const [orgJoinKey, setOldpwd] = useState();
  const [password, setpassword] = useState();
  const [cfpassword, setcfpassword] = useState();
  let {width} = useWindowDimensions();

  let oldpwdprops = {
    placeholder: '填写您的旧密码',
    value: orgJoinKey,
    lefticon: 'lock1',
    type: 'password',
    allowClear: true,
    onChange: val => {
      setOldpwd(val);
    },
  };

  let pwdprops = {
    placeholder: '填写您的新密码',
    value: password,
    lefticon: 'lock1',
    type: 'password',
    allowClear: true,
    onChange: val => {
      setpassword(val);
    },
  };

  let cfpwdprops = {
    placeholder: '确认新密码',
    value: cfpassword,
    lefticon: 'lock1',
    type: 'password',
    allowClear: true,
    onChange: val => {
      setcfpassword(val);
    },
  };

  const nosame = useMemo(() => {
    return password && cfpassword && cfpassword !== password;
  }, [password, cfpassword]);

  const {loading, runAsync} = useRequest(changepwd, {
    manual: true,
  });

  return (
    <View centerH>
      <Mheader
        title={title}
        extraContent={
          <Button
            disabled={
              !orgJoinKey || !password || !cfpassword || nosame || loading
            }
            label="修改"
            size="xsmall"
            backgroundColor={Colors.primaryColor}
            style={{borderRadius: 6, width: 56}}
            iconSource={() => {
              return loading ? (
                <ActivityIndicator color={Colors.primaryColor} />
              ) : null;
            }}
            onPress={async () => {
              await runAsync(
                {
                  password: orgJoinKey,
                  newPassword: password,
                },
                navigation,
              );
            }}
          />
        }
      />

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>旧密码:</Text>
      </View>
      <Input {...oldpwdprops} />

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>新密码:</Text>
      </View>
      <Input {...pwdprops} />

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>确认密码:</Text>
      </View>
      <Input {...cfpwdprops} />
      <View row marginT-18 marginB-12 left width={width / 1.2}>
        {nosame && <Text red30>* 两次密码不一致！</Text>}
      </View>
    </View>
  );
};

const Join = ({title, navigation}) => {
  const dispatch = useDispatch();
  const [orgJoinKey, setOrgJoinKey] = useState();
  let {width} = useWindowDimensions();

  let orgJoinprops = {
    placeholder: '填写您的组织代码',
    value: orgJoinKey,
    lefticon: 'codesquareo',
    type: 'input',
    allowClear: true,
    onChange: val => {
      setOrgJoinKey(val);
    },
  };
  const {loading, runAsync} = useRequest(join, {
    manual: true,
  });

  return (
    <View centerH>
      <Mheader
        title={title}
        extraContent={
          <Button
            disabled={!orgJoinKey || loading}
            label="确定"
            size="xsmall"
            backgroundColor={Colors.primaryColor}
            style={{borderRadius: 6, width: 56}}
            iconSource={() => {
              return loading ? (
                <ActivityIndicator color={Colors.primaryColor} />
              ) : null;
            }}
            onPress={async () => {
              let res = await runAsync(
                {
                  orgJoinKey,
                },
                dispatch,
              );
              if (res.code === 0) {
                navigation.goBack();
              }
            }}
          />
        }
      />

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>组织代码:</Text>
      </View>
      <Input {...orgJoinprops} />
      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text body>* 请填写别人分享的组织代码！</Text>
      </View>
    </View>
  );
};

const Report = ({
  projectId,
  setProjectId,
  remark,
  setRemark,
  workTime,
  setWorkTime,
  iftype,
}) => {
  let {width} = useWindowDimensions();

  let orgJoinprops = {
    placeholder: '填写您花费的工时',
    value: workTime?.toString(),
    lefticon: 'clockcircleo',
    type: 'input',
    allowClear: true,
    keyboardType: 'numeric',
    onChange: val => {
      setWorkTime(val);
    },
  };

  const {data} = useRequest(async () => {
    let res = await get('/project');
    return res.data.dataList ?? [];
  });

  return (
    <View centerH>
      {!iftype && (
        <View row marginT-18 marginB-12 left width={width / 1.2}>
          <Text subheading>选择项目:</Text>
        </View>
      )}
      {!iftype && (
        <Select
          width={width / 1.2}
          value={projectId}
          onChange={setProjectId}
          options={data}
          title="项目"
        />
      )}

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>填写工时(h):</Text>
      </View>
      <Input {...orgJoinprops} />

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>备注:</Text>
      </View>
      <View
        width={width / 1.2}
        left
        top
        style={{
          backgroundColor: Colors.cardbackgroundColor,
          borderRadius: 12,
          padding: 12,
        }}>
        <TextInput
          multiline
          numberOfLines={6} // 设置显示的行数
          placeholder="请输入备注信息"
          value={remark}
          onChangeText={setRemark}
          textAlignVertical="top"
          style={{
            width: '100%',
            height: 166,
          }}
        />
      </View>
      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text body>* 自定义日报</Text>
      </View>
    </View>
  );
};

const MainReport = ({
  projectId,
  setProjectId,
  remark,
  setRemark,
  workTime,
  setWorkTime,
  itemId,
  setItemId,
}) => {
  let {width} = useWindowDimensions();
  let orgJoinprops = {
    placeholder: '填写您花费的工时',
    value: workTime,
    lefticon: 'clockcircleo',
    type: 'input',
    allowClear: true,
    keyboardType: 'numeric',
    onChange: val => {
      setWorkTime(val);
    },
  };

  const {data} = useRequest(async () => {
    let res = await get('/project');
    return res.data.dataList;
  });

  const dls = useRequest(
    async () => {
      let res = await get('/item/getMyMissionSelection', {
        projectId: projectId,
      });
      return res.data.dataList;
    },
    {
      refreshDeps: [projectId],
    },
  );

  return (
    <View centerH>
      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>选择项目:</Text>
      </View>
      <Select
        width={width / 1.2}
        value={projectId}
        onChange={setProjectId}
        options={data}
        title="项目"
      />

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>选择任务:</Text>
      </View>
      <Select
        width={width / 1.2}
        value={itemId}
        onChange={setItemId}
        options={dls?.data ?? []}
        title="任务"
      />

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>填写工时(h):</Text>
      </View>
      <Input {...orgJoinprops} />

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text subheading>备注:</Text>
      </View>
      <View
        width={width / 1.2}
        left
        top
        style={{
          backgroundColor: Colors.cardbackgroundColor,
          borderRadius: 12,
          padding: 12,
        }}>
        <TextInput
          multiline
          numberOfLines={6} // 设置显示的行数
          placeholder="请输入备注信息"
          value={remark}
          onChangeText={setRemark}
          textAlignVertical="top"
          style={{
            width: '100%',
            height: 166,
          }}
        />
      </View>

      <View row marginT-18 marginB-12 left width={width / 1.2}>
        <Text body>* 同任务填写工时</Text>
      </View>
    </View>
  );
};

const AddReport = ({title, workDate, navigation}) => {
  const [index, setIndex] = useState(0);
  const [projectId, setProjectId] = useState(null);
  const [remark, setRemark] = useState(null);
  const [workTime, setWorkTime] = useState(0);
  const [itemId, setItemId] = useState(null);

  const {runAsync, loading} = useRequest(post, {
    manual: true,
    onSuccess: res => {
      if (res.code === 0) {
        DeviceEventEmitter.emit('refreshreport', {
          workDate,
        });
        navigation.goBack();
      }
    },
  });

  const conf = {
    0: {
      key: 'undo',
      text: '任务日报',
      url: '',
    },
    1: {
      key: 'doing',
      text: '自定义日报',
      url: '',
    },
  };

  const props = {
    projectId,
    setProjectId,
    remark,
    setRemark,
    workTime,
    setWorkTime,
    itemId,
    setItemId,
  };

  return (
    <View centerH>
      <Mheader
        title={title}
        extraContent={
          <Button
            disabled={
              !workTime ||
              !projectId ||
              !remark ||
              loading ||
              (index === 0 && !itemId)
            }
            label="确定"
            size="xsmall"
            backgroundColor={Colors.primaryColor}
            style={{borderRadius: 6, width: 56}}
            iconSource={() => {
              return loading ? (
                <ActivityIndicator color={Colors.primaryColor} />
              ) : null;
            }}
            onPress={async () => {
              await Keyboard.dismiss();
              if (index === 0) {
                await runAsync('/itemWorkTime', {
                  workTime,
                  workDate,
                  remark,
                  projectId,
                  itemId,
                });
              } else {
                await runAsync('/itemWorkTime', {
                  workTime,
                  workDate,
                  remark,
                  projectId,
                });
              }
            }}
          />
        }
      />
      <TabController
        items={Object.entries(conf)?.map(([, value]) => ({
          label: value.text,
        }))}
        onChangeIndex={index => {
          setIndex(index);
        }}
        asCarousel={true}>
        <TabController.TabBar
          enableShadows
          spreadItems
          labelColor={Colors.colorTextBase}
          selectedLabelColor={Colors.primaryColor}
          indicatorStyle={{
            backgroundColor: Colors.primaryColor,
          }}
          backgroundColor={Colors.backgroundColor}
        />
        <TabController.PageCarousel flex-1>
          <TabController.TabPage index={0}>
            <MainReport {...props} />
          </TabController.TabPage>
          <TabController.TabPage index={1} lazy>
            <Report {...props} />
          </TabController.TabPage>
        </TabController.PageCarousel>
      </TabController>
    </View>
  );
};

const EidtReport = ({title, workDate, navigation, defaultValue, iftype}) => {
  const [projectId, setProjectId] = useState(defaultValue?.projectId);
  const [remark, setRemark] = useState(defaultValue?.remark);
  const [workTime, setWorkTime] = useState(defaultValue?.workTime);
  useEffect(() => {
    const {projectId, remark, workTime} = defaultValue ?? {};
    setProjectId(projectId);
    setRemark(remark);
    setWorkTime(workTime);
  }, [defaultValue]);

  const {runAsync, loading} = useRequest(update, {
    manual: true,
    onSuccess: async res => {
      if (res.code === 0) {
        DeviceEventEmitter.emit('refreshreport', {
          workDate,
        });
        navigation.goBack();
      }
    },
  });

  const props = {
    projectId,
    setProjectId,
    remark,
    setRemark,
    workTime,
    setWorkTime,
  };

  return (
    <View centerH>
      <Mheader
        title={title}
        extraContent={
          <Button
            disabled={
              !workTime || (!iftype && !projectId) || !remark || loading
            }
            label="确定"
            size="xsmall"
            backgroundColor={Colors.primaryColor}
            style={{borderRadius: 6, width: 56}}
            iconSource={() => {
              return loading ? (
                <ActivityIndicator color={Colors.primaryColor} />
              ) : null;
            }}
            onPress={async () => {
              await Keyboard.dismiss();
              if (iftype) {
                await runAsync('/itemWorkTime/' + defaultValue.id, {
                  workTime,
                  remark,
                });
              } else {
                await runAsync('/itemWorkTime/' + defaultValue.id, {
                  workTime,
                  remark,
                  projectId,
                });
              }
            }}
          />
        }
      />
      <Report {...props} iftype={iftype} />
    </View>
  );
};

export default {EditInfo, ChangePwd, Join, AddReport, EidtReport};
